/**
 * 身份验证工具
 */
import { getUserInfo as fetchUserInfo } from '@/api/user'
import {
	setSessionData,
	getSessionData,
	removeSessionData,
} from './sessionHelper'

// 用于创建用户特定键的函数
function createUserKey(baseKey, username, type) {
	return `${baseKey}_${type}_${username}`
}

/**
 * 获取当前活跃用户
 */
export function getCurrentUser() {
	return getSessionData('currentUser')
}

/**
 * 设置当前活跃用户
 */
export function setCurrentUser(username, type) {
	setSessionData('currentUser', { username, type })
}

/**
 * 移除当前活跃用户
 */
export function removeCurrentUser() {
	removeSessionData('currentUser')
}

/**
 * 获取Token
 */
export function getToken() {
	// 优先从会话存储中获取当前用户
	const currentUser = getCurrentUser()
	if (!currentUser) return null

	// 获取当前用户的token
	return localStorage.getItem(
		createUserKey('token', currentUser.username, currentUser.type)
	)
}

/**
 * 设置Token
 */
export function setToken(token, username, type) {
	if (!username || !type) {
		const userInfo = getUserInfo()
		if (userInfo) {
			username = userInfo.username
			type = userInfo.type
		}
	}

	if (username && type) {
		localStorage.setItem(createUserKey('token', username, type), token)
		// 设置当前活跃用户
		setCurrentUser(username, type)
	}
}

/**
 * 移除Token
 */
export function removeToken(username, type) {
	if (!username || !type) {
		const currentUser = getCurrentUser()
		if (currentUser) {
			username = currentUser.username
			type = currentUser.type
		}
	}

	if (username && type) {
		localStorage.removeItem(createUserKey('token', username, type))
	}
}

/**
 * 获取用户信息
 */
export function getUserInfo(username, type) {
	if (!username || !type) {
		const currentUser = getCurrentUser()
		if (!currentUser) return null

		username = currentUser.username
		type = currentUser.type
	}

	const userInfoStr = localStorage.getItem(
		createUserKey('userInfo', username, type)
	)
	return userInfoStr ? JSON.parse(userInfoStr) : null
}

/**
 * 设置用户信息
 */
export function setUserInfo(userInfo) {
	if (!userInfo || !userInfo.username || !userInfo.type) return

	localStorage.setItem(
		createUserKey('userInfo', userInfo.username, userInfo.type),
		JSON.stringify(userInfo)
	)

	// 设置当前活跃用户
	setCurrentUser(userInfo.username, userInfo.type)
}

/**
 * 移除用户信息
 */
export function removeUserInfo(username, type) {
	if (!username || !type) {
		const currentUser = getCurrentUser()
		if (currentUser) {
			username = currentUser.username
			type = currentUser.type
		}
	}

	if (username && type) {
		localStorage.removeItem(createUserKey('userInfo', username, type))
	}
}

/**
 * 获取登录时间
 */
export function getLoginTime(username, type) {
	if (!username || !type) {
		const currentUser = getCurrentUser()
		if (!currentUser) return null

		username = currentUser.username
		type = currentUser.type
	}

	return localStorage.getItem(createUserKey('loginTime', username, type))
}

/**
 * 设置登录时间
 */
export function setLoginTime(time, username, type) {
	if (!username || !type) {
		const currentUser = getCurrentUser()
		if (!currentUser) return

		username = currentUser.username
		type = currentUser.type
	}

	localStorage.setItem(
		createUserKey('loginTime', username, type),
		time || Date.now().toString()
	)
}

/**
 * 清除登录信息
 */
export function clearLoginInfo(username, type) {
	if (!username || !type) {
		const currentUser = getCurrentUser()
		if (currentUser) {
			username = currentUser.username
			type = currentUser.type
		}
	}

	if (username && type) {
		removeToken(username, type)
		removeUserInfo(username, type)
		localStorage.removeItem(createUserKey('loginTime', username, type))

		// 清除sessionStorage中的当前用户信息
		sessionStorage.removeItem('currentUser')

		// 如果清除的是当前用户，也清除localStorage中的当前用户信息(兼容)
		const localCurrentUser = JSON.parse(
			localStorage.getItem('currentUser') || '{}'
		)
		if (
			localCurrentUser &&
			localCurrentUser.username === username &&
			localCurrentUser.type === type
		) {
			localStorage.removeItem('currentUser')
		}
	}
}

/**
 * 获取所有已登录用户
 */
export function getAllLoggedUsers() {
	const users = []
	for (let i = 0; i < localStorage.length; i++) {
		const key = localStorage.key(i)
		if (key && key.startsWith('userInfo_')) {
			const parts = key.split('_')
			if (parts.length >= 3) {
				const type = parts[1]
				const username = parts.slice(2).join('_') // 处理用户名中可能包含下划线的情况
				const userInfo = getUserInfo(username, type)
				if (userInfo) {
					users.push(userInfo)
				}
			}
		}
	}
	return users
}

/**
 * 更新用户信息（从服务器获取最新信息）
 * @returns {Promise<boolean>} - 是否成功更新
 */
export async function updateUserInfo() {
	const token = getToken()
	if (!token) return false

	try {
		const res = await fetchUserInfo()
		if (res && res.data) {
			setUserInfo(res.data)
			return true
		}
		return false
	} catch (error) {
		return false
	}
}

/**
 * 判断是否为管理员
 */
export function isAdmin() {
	const userInfo = getUserInfo()
	return userInfo && userInfo.type === 'admin'
}

/**
 * 判断是否为学生
 */
export function isStudent() {
	const userInfo = getUserInfo()
	return userInfo && userInfo.type === 'student'
}

/**
 * 获取用户ID
 */
export function getUserId() {
	const userInfo = getUserInfo()
	return userInfo ? userInfo.id : null
}

/**
 * 获取用户名
 */
export function getUserName() {
	const userInfo = getUserInfo()
	return userInfo ? userInfo.name : null
}

/**
 * 切换到已登录的用户
 */
export function switchToUser(username, type) {
	const userInfoKey = createUserKey('userInfo', username, type)
	const userInfoStr = localStorage.getItem(userInfoKey)

	if (userInfoStr) {
		setCurrentUser(username, type)
		return true
	}
	return false
}
